package com.baosight.risk.common.quartz;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.email.service.EmailService;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.HttpUtils;
import com.baosight.risk.common.utils.ReadProperties;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.system.SysInterfaceDataLogMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetSendMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetValueMapper;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JsonConfig;

/**
 * @author cuishihao
 * <p>
 * 定时任务
 * 调用接口获取外部指标数据值  (包含   万德/万得/wind数据)
 */
@Slf4j
@Component("targetValueSendTask")
public class TargetValueSendTask {
    @Autowired
    private ZbaaTargetValueMapper zbaaTargetValueMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private SysInterfaceDataLogMapper logMapper;
    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    private ZbaaTargetSendMapper targetSendMapper;


    public void testParams(String params, String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            log.info("进入定时任务——获取外部指标方法");
            // 获取昨日日期
            String nowDate = DateUtils.format(new Date(), "yyyy-MM-dd");
            String yesterday = DateUtils.caculateTime(nowDate, "日", "1");
            try {

                //对订阅用户发送邮件。通知订阅值发生变化
                emailToOrderUser();
            } catch (Exception e) {
                String str = String.format("%s 获取 %s 外部指标数据出错！", nowDate, yesterday);
                log.info(str);
                log.info(e.toString());
            }
            log.info("定时任务——获取外部指标方法完成");
            logs.add(fltdProcessService.getLog("获取外部指标定时任务执行成功", 0, "", jobId));
        }catch (Exception e) {
            error = e;
            logs.add(fltdProcessService.getLog("获取外部指标定时任务执行失败", 1, e.getMessage(), jobId));
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }
    
    /**
     * @description 对订阅用户发送邮件, 通知订阅值发生变化
     */
    private void emailToOrderUser() {
    	List<String> userCodes = targetSendMapper.queryUserCodes();
    	for(String userCode : userCodes){
    		List<ZbaaTargetValue> targets = zbaaTargetValueMapper.queryNewTargetByUserCode(userCode);
    		
    		List<String> message = new ArrayList<String>(); 
            //遍历信息，发送邮件
            for (ZbaaTargetValue zbaaTargetValue : targets) {
                String stability = "";
                net.sf.json.JSONObject object = null;

                //根据陆家伟的趋势接口,调用,来追加趋势
                List<ZbaaTargetValue> history = zbaaTargetValueMapper.getHistory(zbaaTargetValue.getTargetNo(), 100);
                List<String> resultString = new ArrayList<>();
                for (ZbaaTargetValue tValue:history){
                    resultString.add(tValue.getTargetValue());
                }
                
                List<List<String>> queryDataList = new ArrayList<List<String>>();
                queryDataList.add(resultString);
                Map<String, Object> maps = new HashMap<>();
                maps.put("data", queryDataList);
                try {
                    // 调用Python接口
                    String url = ReadProperties.getValueString("python.threshold.url");
                    String result = HttpUtils.sendJsonPost(url, net.sf.json.JSONObject.fromObject(maps));
                    log.info("预测结果:"+result);
                    if (StringUtils.isNotEmpty(result)) {
                        object = net.sf.json.JSONObject.fromObject(result);
                        System.out.println("预测结果：" + result);
                        List<String> dataList = net.sf.json.JSONArray.toList(object.getJSONArray("data"), new String(), new JsonConfig());
                        List<String> remarkList = net.sf.json.JSONArray.toList(object.getJSONArray("remark"), new String(), new JsonConfig());
                        List<String> statusList = net.sf.json.JSONArray.toList(object.getJSONArray("status"), new String(), new JsonConfig());
                        //新增到扩展字段的趋势
                        List<String> stabilityList = net.sf.json.JSONArray.toList(object.getJSONArray("stability"), new String(), new JsonConfig());
                        stability = stabilityList.get(0);
                    }else {
                        throw new RuntimeException(result);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                
                message.add("您订阅的指标" + zbaaTargetValue.getTargetName() + "在" + DateUtils.format(zbaaTargetValue.getCreateTime(), "yyyy-MM-dd") + "更新为" + zbaaTargetValue.getTargetValue() + ";最近指标趋势为" + stability);

            }
            //调用邮箱接口发邮件。
            int result = emailService.sendEmail(userCode, "订阅的指标更新提示", StringUtils.join(message, "\n"), "");
            System.out.println(result);
    	}
    }

    /**
     * @param periodNo 周期
     * @return
     * @description 描述
     * @author CuiShiHao
     */
    public String dealQuarter(String periodNo) {
        String year = periodNo.substring(0, 4);
        String month = periodNo.substring(4, 6);
        String result = "";
        switch (month) {
            case "1":
            case "2":
            case "3":
                result = "Q1";
                break;
            case "4":
            case "5":
            case "6":
                result = "Q2";
                break;
            case "7":
            case "8":
            case "9":
                result = "Q3";
                break;
            case "10":
            case "11":
            case "12":
                result = "Q4";
                break;
        }
        return year + result;
    }

    public void testNoParams() {
        log.error("执行无参方法");
    }
}
